<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="产品名称" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item v-model="dataForm.logo" label="logo图片" prop="logo">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item
        title="上传文件"
        label="上传文件" prop="logo"
        :close-on-click-modal="false"
        :visible.sync="visible">
        <el-upload
          drag
          :action="url"
          :before-upload="beforeUploadHandle"
          :on-success="successHandle"
          multiple
          :file-list="fileList"
          style="text-align: center;">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只支持jpg、png、gif格式的图片！</div>
        </el-upload>
      </el-form-item>      -->
      <el-form-item label="所属贷超"  prop="marketIds">
        <el-checkbox-group v-model="dataForm.marketIds">
          <el-checkbox v-for="market in marketList" :key="market.id" :label="market.id">{{ market.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="分类"  prop="types">
        <el-checkbox-group v-model="dataForm.types">
          <el-checkbox label="1">秒下款</el-checkbox>
          <el-checkbox label="2">无门槛</el-checkbox>
          <el-checkbox label="3">低息贷款</el-checkbox>
          <el-checkbox label="4">热门推荐</el-checkbox>
          <el-checkbox label="5">高通过</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- <el-form-item label="人数" prop="number" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.number"  placeholder="人数" type="number"></el-input>
      </el-form-item> -->
      <el-form-item label="贷款最低金额" prop="minAmount">
        <el-input v-model="dataForm.minAmount" placeholder="贷款最低金额" type="number"></el-input>
      </el-form-item>
      <el-form-item label="贷款最大金额" prop="maxAmount">
        <el-input v-model="dataForm.maxAmount" placeholder="贷款最大金额" type="number"></el-input>
      </el-form-item>
      <el-form-item label="利率类型" size="mini" prop="rateType">
        <el-radio-group v-model="dataForm.rateType">
          <el-radio :label="1">日利率</el-radio>
          <el-radio :label="2">月利率</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="利率" prop="rate">
        <el-input v-model="dataForm.rate" placeholder="利率" type="number"></el-input>
      </el-form-item>
      <el-form-item label="贷款最小天数" prop="minDay">
        <el-input v-model="dataForm.minDay" placeholder="贷款最小天数" type="number"></el-input>
      </el-form-item>
      <el-form-item label="贷款最大天数" prop="maxDay">
        <el-input v-model="dataForm.maxDay" placeholder="贷款最大天数" type="number"></el-input>
      </el-form-item>
      <el-form-item label="申请条件" prop="requirement">
        <el-input v-model="dataForm.requirement" placeholder="申请条件" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="所需材料" prop="needData">
        <el-input v-model="dataForm.needData" placeholder="所需材料" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="最快放款" prop="loanTime">
        <el-input v-model="dataForm.loanTime" placeholder="最快放款" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="审核方式" prop="auditMethod">
        <el-input v-model="dataForm.auditMethod" placeholder="审核方式" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="认证信息" prop="authInfo">
        <el-input v-model="dataForm.authInfo" placeholder="认证信息" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="label">
        <el-input v-model="dataForm.label" placeholder="标签" maxlength="100"></el-input>
      </el-form-item>
       <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">上线</el-radio>
          <el-radio :label="2">下线</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品链接" prop="url">
        <el-input v-model="dataForm.url" placeholder="产品链接" maxlength="500"></el-input>
      </el-form-item>
      <el-form-item label="产品描述" prop="productDesc">
        <el-input v-model="dataForm.productDesc" placeholder="产品描述" maxlength="200"></el-input>
      </el-form-item>
      <el-form-item label="权重" prop="weight">
        <el-input v-model="dataForm.weight" placeholder="权重" maxlength="20"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50x;
    height: 50px;
    display: block;
  }
</style>
<script>
  export default {
    data () {
      var validateNumber = (rule,value,callback) => {
        if(value === ''){
          callback(new Error('人数不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('人数必须大于0'));
          }
          callback();
        }
      };
      var validateMinAmount = (rule,value,callback) => {
        if(value === ''){
          callback(new Error('贷款最低金额不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('贷款最低金额必须大于0'));
          }else{
            if(Number(value)>Number(this.dataForm.maxAmount) && Number(this.dataForm.maxDay)>0){
              callback(new Error('贷款最低金额不能大于贷款最高金额'));
            }
          }
          callback();
        }
      };
      var validateMaxAmount = (rule,value,callback) => {
        if(value === ''){
          callback(new Error('贷款最高金额不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('贷款最高金额必须大于0'));
          }
          callback();
        }
      };
       var validateRate= (rule,value,callback) => {
        if(value === ''){
          callback(new Error('利率不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('利率必须大于0'));
          }
          callback();
        }
      };
      var validateMinDay= (rule,value,callback) => {
        if(value === ''){
          callback(new Error('贷款最小天数不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('贷款最小天数必须大于0'));
          }else{
            if(Number(value.val) >this.dataForm.maxDay && Number(this.dataForm.maxDay.val)>0){
              callback(new Error('贷款最小天数不能大于贷款最大天数'));
            }
          }
          callback();
        }
      };
      var validateMaxDay= (rule,value,callback) => {
        if(value === ''){
          callback(new Error('贷款最大天数不能为空'));
        }else{
          if(value <= 0){
            callback(new Error('贷款最大天数必须大于0'));
          }
          callback();
        }
      };
      return {
        visible: false,
        marketList: [],
        url: '',
        fileList: [],
        dataForm: {
          id: 0,
          name: '',
          number: '',
          maxAmount: '',
          minAmount: '',
          rateType: '',
          rate: '',
          maxDay: '',
          minDay: '',
          requirement: '',
          needData: '',
          loanTime: '',
          auditMethod: '',
          authInfo: '',
          label: '',
          url: '',
          productDesc: '',
          weight: '',
          marketList: [],
          status: 1,
          types: [],
          marketIds: [],
          logo: '',
          imageUrl: ''
        },
        dataRule: {
          name: [
            { required: true, message: '产品名不能为空', trigger: 'blur' }
          ],
          marketIds: [
            { required: true, message: '所属贷超不能为空', trigger: 'blur' }
          ],
          types: [
            { required: true, message: '分类不能为空', trigger: 'blur' }
          ],
          // number: [
          //  { required: true, validator:validateNumber, trigger: 'blur' }
          // ],
          minAmount: [
            { required: true, validator:validateMinAmount, trigger: 'blur' }
          ],
          maxAmount: [
           { required: true, validator:validateMaxAmount, trigger: 'blur' }
          ],
          rateType: [
            { required: true, message: '利率类型不能为空', trigger: 'blur' }
          ],
          rate: [
            { required: true, validator:validateRate, trigger: 'blur' }
          ],
          minDay: [
            { required: true, validator:validateMinDay, trigger: 'blur' }
          ],
          maxDay: [
            { required: true, validator:validateMaxDay, trigger: 'blur' }
          ],
          requirement: [
            { required: true, message: '所需材料不能为空', trigger: 'blur' }
          ],
          loanTime: [
            { required: true, message: '最快放款不能为空', trigger: 'blur' }
          ],
          auditMethod: [
            { required: true, message: '审核方式不能为空', trigger: 'blur' }
          ],
          authInfo: [
            { required: true, message: '认证信息不能为空', trigger: 'blur' }
          ],
          auditMethod: [
            { required: true, message: '审核方式不能为空', trigger: 'blur' }
          ],
          label: [
            { required: true, message: '标签不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '状态不能为空', trigger: 'blur' }
          ],
          url: [
            { required: true, message: '产品链接不能为空', trigger: 'blur' }
          ],
          productDesc: [
            { required: true, message: '产品描述不能为空', trigger: 'blur' }
          ],
          weight: [
            { required: true, message: '权重不能为空', trigger: 'blur' }
          ],
          logo: [
            { required: true, message: 'logo不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.imageUrl = ''
        this.$http({
          url: this.$http.adornUrl('/api/market/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.marketList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/api/product/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.product.name
                // this.dataForm.number = data.product.number
                this.dataForm.maxAmount = data.product.maxAmount
                this.dataForm.minAmount = data.product.minAmount
                this.dataForm.rateType = data.product.rateType
                this.dataForm.rate = data.product.rate
                this.dataForm.maxDay = data.product.maxDay
                this.dataForm.minDay = data.product.minDay
                this.dataForm.requirement = data.product.requirement
                this.dataForm.needData = data.product.needData
                this.dataForm.loanTime = data.product.loanTime
                this.dataForm.auditMethod = data.product.auditMethod
                this.dataForm.authInfo = data.product.authInfo
                this.dataForm.label = data.product.label
                this.dataForm.url = data.product.url
                this.dataForm.productDesc = data.product.productDesc
                this.dataForm.weight = data.product.weight
                this.dataForm.status = data.product.status
                this.dataForm.types = data.product.types
                this.dataForm.marketIds = data.product.marketIds
                this.dataForm.logo = data.product.logo
                this.imageUrl = data.product.logo
              }
            })
          }
        })
      },
      handleAvatarSuccess (res, file) {
        this.imageUrl = res.url
        this.dataForm.logo = res.url
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg'||'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      // // 上传之前
      // beforeUploadHandle (file) {
      //   if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //     this.$message.error('只支持jpg、png、gif格式的图片！')
      //     return false
      //   }
      //   this.num++
      // },
      // // 上传成功
      // successHandle (response, file, fileList) {
      //   this.fileList = fileList
      //   this.successNum++
      //   if (response && response.code === 0) {
      //     this.dataForm.logo = response.url
      //     if (this.num === this.successNum) {
      //       this.$confirm('操作成功, 是否继续操作?', '提示', {
      //         confirmButtonText: '确定',
      //         cancelButtonText: '取消',
      //         type: 'warning'
      //       }).catch(() => {
      //         this.visible = false
      //       })
      //     }
      //   } else {
      //     this.$message.error(response.msg)
      //   }
      // },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/api/product/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'successRate': this.dataForm.successRate,
                'number': this.dataForm.number,
                'maxAmount': this.dataForm.maxAmount,
                'minAmount': this.dataForm.minAmount,
                'rateType': this.dataForm.rateType,
                'rate': this.dataForm.rate,
                'maxDay': this.dataForm.maxDay,
                'minDay': this.dataForm.minDay,
                'requirement': this.dataForm.requirement,
                'needData': this.dataForm.needData,
                'loanTime': this.dataForm.loanTime,
                'auditMethod': this.dataForm.auditMethod,
                'authInfo': this.dataForm.authInfo,
                'payMethod': this.dataForm.payMethod,
                'label': this.dataForm.label,
                'url': this.dataForm.url,
                'productDesc': this.dataForm.productDesc,
                'weight': this.dataForm.weight,
                'status': this.dataForm.status,
                'marketIds': this.dataForm.marketIds,
                'types': this.dataForm.types,
                'logo': this.dataForm.logo,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }else{
            return false;
          }
        })
      }
    }
  }
</script>
